<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015/8/12
 * Time: 10:03
 */

namespace App\Console\Commands;


use App\Services\ApiConfigService;
use Illuminate\Filesystem\Filesystem;

class MakeRoutesCommand extends BaseCommand
{
    /**
     * @var \Illuminate\Filesystem\Filesystem
     */
    protected $files;

    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'create:routes';
    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = "根据 config/api.*.php 文件，生成 routes.auto_generate.php ";

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function fire()
    {
        $this->makeRoutes();

    }

    protected function getRoutes()
    {

        $dir = __DIR__ . "/../../config/";
        $files = new Filesystem();
        $configs = $files->glob($dir . "api.*.php");

        foreach ($configs as $config) {
            $pathInfo = pathinfo($config);
            $filename = $pathInfo['filename'];
            app()->configure($filename);
        }
        $apiDefs = config('api');

        $result = [];
        foreach ($apiDefs as $apiDef) {
            if (!isset($apiDef['methods'])) {
                echo json_encode($apiDef) ;
                continue;
            }
            foreach ($apiDef['methods'] as $method) {

                $matrix = explode('\\', $apiDef['controller']);

                $action = [
                    'uses' => $matrix[count($matrix) - 1] . '@' . $method['method'],
                ];

                $action['middleware'] = [];
                if (isset($method['middleware'])) {
                    $action['middleware'] = $method['middleware'];
                }
                array_push($action['middleware'], 'api');

                $route = [
                    "method" => $method,
                    "action" => $action
                ];

                array_push($result, $route);
                // app()->addRoute($method['requestMethod'], $method['requestRoute'], $action);
            }
        }
        return $result;
    }

    public function makeRoutes()
    {
        $service = new ApiConfigService();
        $routes = $this->getRoutes();
        $data = [
            "routes" => $routes
            , "dollar" => '$'
        ];
        $content = view('stubs/routes', $data);
        // var_dump($content);

        $this->files = new Filesystem();
        $basePath = app()->basePath();
        $filePath = $basePath . "/app/Http/routes.auto_generate.php";
        $this->files->put($filePath, $content);

        echo $filePath . " generated\n";
    }


}